#include <iostream>
#include <vector>

#include <map>
#include <set>

#include <cassert>

#include <sds/sds.h>

#include <matrix.h>
#include <cluster.h>
#include <random.h>

using namespace std;
using namespace sds;

void calculate_dfs(int i, int j, int n, int c, 
		 SDataView<unsigned char>& col, int& num) {
  if (i < 0 || j < 0 || i >= col.getSize()[0] || j >= col.getSize()[1] ||
      col[i][j] != c) return;
  col[i][j] = 255;
  calculate_dfs(i - 1, j, n, c, col, num);
  calculate_dfs(i + 1, j, n, c, col, num);
  calculate_dfs(i, j - 1, n, c, col, num);
  calculate_dfs(i, j + 1, n, c, col, num);
  ++num;
}

void calculate(SDataView<unsigned char>& col, int &num,
	       double& sum, double& sqr, int& black) {
  num = 0; sum = 0.0; sqr = 0.0; black = 0;
  for (int i = 0; i < col.getSize()[0]; ++i) {
    for (int j = 0; j < col.getSize()[1]; ++j) {
      if (col[i][j] == 255) {
	continue;
      }
      if (col[i][j] != 0) {
	int n = 0;
	calculate_dfs(i, j, n, col[i][j], col, n);
	sum += n;
	sqr += n * n;
	++num;
      } else {
	++black;
      }
    }
  }
}


int main(int argc, const char *argv[]) {
  assert(argc == 2);

  vector<SInteger> size;

  SFile segfile(argv[1]);
  SDataView<unsigned char> seg = 
    segfile.getDataset(0).getDataView<unsigned char>();
  size = seg.getSize();

  int num, black;
  double sum, sqr;
  calculate(seg, num, sum, sqr, black);
  
  cout << "Pontok szama: " << size[0] * size[1] << endl;
  cout << "Szegmensek szama: " << num << endl;
  cout << "Szegmensek atlagos merete: " << sum / num << endl;
  cout << "Szegmensmeret szorasa: " << 
    sqrt((sqr - sum * sum / num) / (num - 1)) << endl;
  cout << "Nem szegmentalt pontok szama: " << black << endl;

  return 0;
}
